const co = require('co');
const axios = require('axios');
const X2JS = require('x2js');
const pay = require('./pay');
const logger = require('../utils/logger');

// 快捷支付
const quickPayAddress = process.env.QUICK_PAY_ADDRESS;
const quickPayMerchantID = process.env.QUICK_PAY_MERCHANT_ID;
const quickPayKey = process.env.QUICK_PAY_MERCHANT_KEY;

function quickPaySign(params) {
    return pay.sign(params, quickPayKey);
}

function getQuickPaySignedXml(params) {
    return pay.getSignedXml(params, quickPayKey);
}

let quickPay = co.wrap(function *(billno, amount, notifyUrl) {
    let params = {
        version: '1.0',
        spid: quickPayMerchantID,
        spbillno: billno,
        tran_amt: amount * 100,
        notifyUrl: notifyUrl
    };
    let xmlData = getQuickPaySignedXml(params);
    logger.info(xmlData);

    let resp = yield axios.post(quickPayAddress, xmlData, {
        headers: { 'Content-Type': 'text/xml' }
    });
    logger.info(resp.data);

    let x2js = new X2JS();
    return x2js.xml2js(resp.data).xml;
});

module.exports = {
    quickPaySign,
    getQuickPaySignedXml,
    quickPay,
    quickPayMerchantID
};